package cn.hzc.fortess.system.controller;


import cn.hzc.fortess.config.properties.SamProperties;
import cn.hzc.fortess.core.common.ResponseData;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import springfox.documentation.annotations.ApiIgnore;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.UUID;

/**
 * 验证码生成
 */
@Api(tags = {"登录验证码生成"})
@Controller
@RequestMapping("/kaptcha")
public class KaptchaController {


    private static final Logger log = LoggerFactory.getLogger(KaptchaController.class);

    @Autowired
    private SamProperties samProperties;


    //see WebConfig.java
    @Autowired
    private Producer producer;


    /**
     * 生成验证码
     */
    @ApiOperation("生成验证码")
    @RequestMapping(value = "",method = RequestMethod.GET)
    public void generateKaptcha(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();

        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");


        final String capText = producer.createText();
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
        BufferedImage bi = producer.createImage(capText);
        log.info("生成验证码:{}", capText);
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            ImageIO.write(bi, "jpg", out);
            out.flush();
        } catch (IOException e) {
            session.removeAttribute(Constants.KAPTCHA_SESSION_KEY);
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (Exception e) {
            }
        }
    }

    @ApiIgnore
    @RequestMapping("/{pictureId}")
    public void renderPicture(@PathVariable("pictureId") String pictureId, HttpServletResponse response) {
        String path = samProperties.getFileUploadPath() + pictureId;
        try {

            byte[] bytes = toByteArray(path);
            response.getOutputStream().write(bytes);
        } catch (Exception e) {
        }
    }


    @ApiOperation("生成令牌")
    @RequestMapping(value = "/token",method = RequestMethod.POST)
    @ResponseBody
    public ResponseData generateToken(HttpServletRequest request) {
        HttpSession session = request.getSession();
        String token = UUID.randomUUID().toString();
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, token);
        return ResponseData.success(token);
    }

    private static byte[] toByteArray(String filename) {
        File f = new File(filename);

        FileChannel channel = null;
        FileInputStream fs = null;
        try {
            fs = new FileInputStream(f);
            channel = fs.getChannel();
            ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
            while ((channel.read(byteBuffer)) > 0) {
            }
            return byteBuffer.array();
        } catch (IOException e) {
        } finally {
            try {
                channel.close();
            } catch (IOException e) {
            }
            try {
                fs.close();
            } catch (IOException e) {
            }
        }
        return null;
    }

}
